/**
 * 
 */
package com.geezdata.cps.base.shiro;

import java.lang.annotation.Annotation;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;

import com.geezdata.cps.base.annotation.NoShiro;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

/**
 * @author sszheng
 * @date 创建时间：2018年5月30日 下午4:45:57
 *
 */
@Component
public class NoShiroPostProcessor implements PriorityOrdered, BeanDefinitionRegistryPostProcessor {
    private final static Logger LOG = LoggerFactory.getLogger(NoShiroPostProcessor.class);
    
    private static List<String> instance;

    public static List<String> getInstance(){
        if(instance == null){
            synchronized (NoShiroPostProcessor.class){
                if(instance==null){
                    instance = Lists.newArrayList();
                }
            }
        }
        return instance;
    }
    
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
    
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("postProcessBeanFactory");
        }
        
        String[] ary = beanFactory.getBeanNamesForAnnotation(NoShiro.class);
        if (ary != null && ary.length>0) {
            for(String beanName : ary) {
                Class<?> cls = beanFactory.getType(beanName);
                if (cls.getAnnotations()!=null && cls.getAnnotations().length>0) {
                    for (Annotation annotation : cls.getAnnotations()) {
                        if (annotation instanceof NoShiro) {
                        	NoShiro intfc = (NoShiro) annotation;
                        	if(StringUtils.isNotEmpty(intfc.name())) {
                        		getInstance().addAll(Splitter.on(",").splitToList(intfc.name()));
                        	}
                        }
                    }
                }
            }
        }
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("postProcessBeanDefinitionRegistry");
        }
    }
}